package com.zmjmall.demo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zmjmall.demo.properties.LoginProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * 登录拦截器实现HandlerInterceptorAdapter
 *
 * @author zmj
 * @version 2018/7/3
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LoginProperties loginProperties;

    @Autowired
    private ObjectMapper objectMapper;

    private AntPathMatcher pathMatcher = new AntPathMatcher();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 对来自后台的请求统一进行拦截 判断是否携带token
         */
        /*String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();

        String logInfo = String.format("请求参数, url: %s, method: %s, uri: %s", url, method, uri);
        String interceptUrls = loginProperties.getInterceptorurls();
        log.info("[请求路径] : {}",logInfo);
        boolean action = false;
        if(interceptUrls != null  ) {
            String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(interceptUrls,",");
            for (String conUrl:configUrls) {
                if(pathMatcher.match(conUrl,request.getRequestURI())) {
                    action = true;
                }
            }
        }
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");

        if(action) {
            //查询cookie
            Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
            if(null == cookie){
                log.warn("[登录校验] , cookie 中查不到token, {}",logInfo);
                response.getWriter().write(objectMapper.writeValueAsString(
                        ResultVOUtil.error(ResultEnum.FAILURE_NOTCOOKILE_TOKEN.getCode(),
                                ResultEnum.FAILURE_NOTCOOKILE_TOKEN.getMsg())));
                return false;
            }
            //查询redis
            String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
            if(StringUtils.isEmpty(tokenValue)){
                log.warn("[登录校验] Redis中查不到token, {}",logInfo);
                response.getWriter().write(objectMapper.writeValueAsString(
                        ResultVOUtil.error(ResultEnum.FAILURE_NOTREDIS_TOKEN.getCode(),
                                ResultEnum.FAILURE_NOTREDIS_TOKEN.getMsg())));
                return false;
            }
        }
        return true;
        */
       return super.preHandle(request,response,handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
